<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;">
			<el-table-column type="index" label="序号" width="60" align='center'>
				<template slot-scope="scope">   
                    {{pageSize*(nowPage-1)+scope.$index+1}}
                </template>
			</el-table-column>
			<el-table-column prop="roleName" label="角色名称" min-width="200" align='center' >
			</el-table-column>
			<el-table-column label="角色层级" min-width="150" align='center'>
				<template slot-scope="scope">
					{{scope.row.roleLevel=="0"?"超级管理员":(scope.row.roleLevel=="1"?"平台管理员":"校级管理员")}}
				</template>
			</el-table-column>
			<el-table-column label="状态" width="100" align='center'>
				<template slot-scope="scope">
					{{scope.row.useType==0?"可用":"停用"}}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="290" align='center' fixed="right">
				<template slot-scope="scope">
					<el-button v-if="scope.row.roleLevel!='0'" type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button v-if="scope.row.roleLevel!='0'" type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button v-if="scope.row.useType==0 && scope.row.roleLevel!='0'" type="info" size="small" @click="offRole(scope.row)">停用</el-button>
					<el-button v-else-if="scope.row.roleLevel!='0'"  type="success" size="small"  @click="onRole(scope.row)">启用</el-button>
					<el-button v-if="scope.row.roleLevel!='0'" type="warning" size="small" @click="assignAuthority(scope.row)">权限</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="text-align: center; ">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="editType" :visible.sync="editFormVisible" :close-on-click-modal="false" :before-close="closeDialog" :append-to-body="true" v-loading="editLoading">
			<el-form :model="roleForm" label-width="120px" :rules="roleRules" ref="roleForm">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="roleForm.roleName" placeholder="请输入角色名称，最长30个汉字" style="float:left;width:77%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="角色层级" prop="roleLevel">
					<el-select v-model="roleForm.roleLevel" placeholder="请选择角色层级" :style="{width: '77%'}">
						<el-option v-for="(item, index) in roleLevelOptions" :key="index" :label="item.label"
							:value="item.value" :disabled="item.disabled"></el-option>
					</el-select>
     			</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="closeDialog">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--权限分配-->
		<el-dialog title="权限分配" v-if="assignAuthorityDialog" :visible.sync="assignAuthorityDialog" @close="closeAssignAuthority()" width="50%">
			<el-tree :data="assignAuthorityJson" :props="assignAuthorityProps" 
				:default-expanded-keys="assignAuthorityExpanded"
				:default-checked-keys="assignAuthorityChecked"
				ref="tree" show-checkbox node-key="menuId"></el-tree>
			<span slot="footer" class="dialog-footer">
				<el-button @click="closeAssignAuthority()">取 消</el-button>
				<el-button type="primary" @click="trueAssignAuthority()">确 定</el-button>
			</span>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	import { SysApi } from '@/api/index'

	export default {
		data() {
			return {
				filters: {
				},
				tableData: [],
				total: 0,
				listLoading: true,

				//角色信息表单
				roleForm: {
					roleId: '',
					roleName: ''
				},
				roleLevelOptions: [{
					"label": "平台管理员",
					"value": 1
				}, {
					"label": "校级管理员",
					"value": 2
				}],

				editType: '',

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				roleRules: { //角色信息表单验证
					roleName:[
						{ required: true, message: '请填写角色名称', trigger: 'blur' },
						{ min: 1, max: 30, message: '角色名称长度为 1 到 30 个字符', trigger: ['blur','change'] }
					],
					roleLevel:[
						{ required: true,  message: '请选择角色层级', trigger: ['blur','change']}
					]
            },

			assignAuthorityDialog: false,//权限分配控制
			assignAuthorityJson: [], //权限分配数据
            assignAuthorityProps: {id:'menuId', children: 'sonMenuList', label: 'menuName'},
            assignAuthorityChecked: [],
            assignAuthorityExpanded: [],

            pageSize:10,
            nowPage:1,

			}
		},
		created(){
			this.getRoles();

		},
		mounted() {
			this.getRoles();
		},
		methods: {

			handleCurrentChange(val) {
				this.nowPage = val;
				this.getRoles();
			},
			//获取角色列表
			getRoles() {
				let params = {
					pageNum: this.nowPage,
					pageSize: this.pageSize,
				};
				this.listLoading = true;

				SysApi.getALLRoleListPage(params,res =>{
					this.total = res.total;
					this.tableData = res.list;
					this.listLoading = false;
				}, (errorType, error) => {
					this.listLoading = false;
				})


			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
	
					let params = {
						 roleId: row.roleId
						 };

					SysApi.deleteRole(params,res =>{
						this.listLoading = false;
						if (res!=null)
						{
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.getRoles();
					}, (errorType, error) => {
						this.listLoading = false;
					}).catch((error) => {
						this.listLoading = false;
					})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editType = "编辑";
				this.editLoading = true;
				this.roleForm = Object.assign({}, row);
				this.editFormVisible = true;
				this.editLoading = false;
				
			},
			//显示新增界面
			handleAdd: function () {
				this.editType = "新增";
				this.editLoading = true;

				this.roleForm.roleId =  '';
				this.roleForm.roleName =  '';
				this.roleForm.phaseId =  '';
				this.roleForm.yearNum =  '';
				this.roleForm.phaseName =  '';

				this.editFormVisible = true;
				this.editLoading = false;
		
			},
			//编辑
			editSubmit: function () {
				this.$refs.roleForm.validate((valid) => {
					if (valid) {
							
							let params = Object.assign({}, this.roleForm);
							
							SysApi.saveRole(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['roleForm'].resetFields();
								this.editFormVisible = false;
								this.getRoles();
							}, (errorType, error) => {
								this.$message({type: 'error', message: '提交失败!'})
								
	
							})
							
					}
				});
			},
			closeDialog: function () {
				
				this.$refs['roleForm'].resetFields();
				this.editFormVisible = false;
			},
			onRole(row){
				this.$confirm('是否启用角色?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.onRole({
						roleId: row.roleId
					}, res => {
						this.$message({type: 'success', message: '启用成功!'})
						this.getRoles();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '启用失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			offRole(row) {
				this.$confirm('是否停用角色?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.offRole({
						roleId: row.roleId
					}, res => {
						this.$message({type: 'success', message: '停用成功!'})
						this.getRoles();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '停用失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			//分配权限
			assignAuthority(row){
				this.roleId = row.roleId;
				
				let params = {
					productLevel: 1,
					roleLevel: row.roleLevel
				}
	
				SysApi.getMenusByProductLevel(params,res =>{
					this.assignAuthorityJson = res.menuList;
					this.assignAuthorityExpanded = res.menuParentIds;
					this.assignAuthorityChecked = row.menuIds;
					this.assignAuthorityDialog = true;
				}, (errorType, error) => {
					this.$message({type: 'error', message: '查询菜单失败!'})
					// console.log("error=");
					// console.log(error);

				})
			},
			//分配权限(确定按钮)
			trueAssignAuthority(){
				let menuIds = this.$refs.tree.getCheckedKeys();//.concat(this.$refs.tree.getHalfCheckedKeys());
				
				if(menuIds.length == 0){
					this.$message({
						message: '至少勾选一个权限',
						type: 'warning'
					});
					return;
				}
				let params = {
					roleId: this.roleId,
					menuIds: menuIds
				}
			
				SysApi.saveRoleMenu(params,res =>{
					this.$message({
							message: '分配成功',
							type: 'success'
						});
						this.getRoles();
						this.closeAssignAuthority();
				}, (errorType, error) => {
					this.$message({type: 'error', message: '查询菜单失败!'})
					// console.log("error=");
					// console.log(error);

				})
			},
			//分配权限(弹窗关闭处理)
			closeAssignAuthority(){
				this.assignAuthorityJson = [];
				this.assignAuthorityExpanded = [];
				this.assignAuthorityChecked = [];
				this.assignAuthorityDialog = false;
			}

		},
		
	}

</script>

<style>
.el-table >.el-table__fixed {
    height: 100% !important; 
  }
.el-table >.el-table__fixed-right {
    height: 100% !important; 
  }
.el-table--scrollable-x .el-table__body-wrapper {
    z-index: 1;
  }
</style>